/*!
 * Page: pages/blacklist/Blacklist
 * License: MIT
 * Created: 2019-10-15 17:02
 */
import { userApi } from '/api/user'
Page({
  data: {
    blacks: [] as DomoUser[],
    loading: false,
    canLoad: true,
    deleting: 0,
  },
  onShow() {
    this.fetchBlacks()
  },
  /** 下拉刷新 */
  async onPullDownRefresh() {
    await this.fetchBlacks()
    wx.stopPullDownRefresh()
  },
  /** 触底加载更多 */
  onReachBottom() {
    this.fetchBlacks(true)
  },
  remove(e: any) {
    const {
      currentTarget: {
        dataset: {
          user: { id },
        },
      },
    } = e
    this.setData(
      {
        deleting: id,
      },
      () => {
        userApi.unBlack(id).then(() => {
          this.setData({
            deleting: 0,
            blacks: this.data.blacks.filter((i) => i.id !== id),
          })
        })
      },
    )
  },
  fetchBlacks(loadMore = false) {
    const limit = 15
    const {
      data: { blacks, loading, canLoad },
    } = this
    // 如果不能加载更多，返回
    if (!canLoad && loadMore) return
    if (!loading) {
      this.setData({ loading: true })
      const query = {
        limit,
        offset: 0,
      }
      // 如果是加载更多
      if (loadMore) {
        query.offset = blacks.length
      }
      userApi
        .blacks(query)
        .then((data) => {
          this.setData({
            blacks: loadMore ? [...blacks, ...data] : data,
            loading: false,
            canLoad: data.length === limit,
          })
        })
        .catch((error) => {
          console.log(error)
        })
    }
  },
})
